package com.lightbend.akka.np_sharding

import akka.actor.{ActorRef, ActorSystem, Props}
import akka.cluster.sharding.{ClusterSharding, ClusterShardingSettings}
import akka.stream.ActorMaterializer
import com.lightbend.akka.np_sharding.Counter.Increment
import com.lightbend.akka.np_sharding.CounterClusterConfig.{EntityEnvelope, Get}

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}

object Boot extends App {

  implicit val system      : ActorSystem       = ActorSystem("Sharding-no-persistence")
  implicit val ec          : ExecutionContext  = system.dispatcher
  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val counterRegion: ActorRef = ClusterSharding(system).start(
    typeName = "SupervisedCounter",
    entityProps = Props[CounterSupervisor],
    settings = ClusterShardingSettings(system),
    extractEntityId = CounterClusterConfig.extractEntityId,
    extractShardId = CounterClusterConfig.extractShardId)

  // scheduler sender message
  system.scheduler.schedule(0.second,
    5.seconds,
    new Runnable {
      override def run(): Unit = {
        val id = java.util.UUID.randomUUID.toString
        counterRegion ! Get(id)
        counterRegion ! EntityEnvelope(id, Increment)
      }
    }
  )

  sys.addShutdownHook {
    Await.result(system.whenTerminated, Duration.Inf)
  }
}
